<?php


namespace App\Resource\Repository;


use App\Resource\Model\CategoryModel;
use App\Resource\Model\CrdCategoryModel;
use Hyperf\Database\Concerns\BuildsQueries;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;

class CategoryRepository implements BaseRepositoryInterface
{
    /**
     * @param array|string[] $field
     * @param array $where
     * @param string $whereRaw
     * @param bool $isArray
     * @return array|BuildsQueries|Builder|Model|mixed|object|null
     * @author zhangzhiyuan
     * mailbox 466180170@qq.com
     */
    public function findFirst(array $field = ['*'],array $where = [],string $whereRaw='',bool $isArray=true)
    {
        $connect = CategoryModel::query()->select($field)
            ->when($where, function ($query) use ($where){
                return $query->where($where);
            })
            ->when($whereRaw, function ($query) use($whereRaw){
                return $query->whereRaw($whereRaw);
            })
            ->first();
        if($isArray) return empty($connect) ? array():$connect->toArray();
        return $connect;
    }

    /**
     * 主表查询多条
     * @param array $where
     * @param array|string[] $field
     * @param bool $isArray
     * @return array|Builder|Model|object|null
     * @author zhangzhiyuan
     */
    public function selectListNoPage(array $field,array $where,array $orderBy,$source,bool $isArray=true)
    {
        if ($source == 1) $query = CategoryModel::query(); elseif ($source == 2) {
            $query = CrdCategoryModel::query();
        }
        $connect = $query->select($field)
            ->when($where, function ($query) use ($where){
                return $query->where($where);
            })
            ->when($orderBy, function ($query) use($orderBy){
                return $query->orderBy($orderBy[0],$orderBy[1]);
            }, function ($query) {
                return $query->orderBy('sort','asc');
            });
        if($isArray) return empty($connect) ? ['count' => $connect->count(), 'list' =>[]]:['count' => $connect->count(), 'list' => $connect->get()->toArray()];
        return $connect;
    }

    public function getResourceSingleSonByPrimaryId(int $PrimaryId, array $PrimaryField, array $SonField)
    {
        // TODO: Implement getMergeSingleSonByPrimaryId() method.
    }

}